package net.kehuilai.config;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

@Configuration
@EnableDynamoDBRepositories
        (basePackages = "net.kehuilai.repositories.dynamodb")
public class DynamoDBConfig implements EnvironmentAware {
    private String amazonDynamoDBEndpoint;

    @Bean
    public AmazonDynamoDB amazonDynamoDB() {
        AWSCredentials credentials = new ProfileCredentialsProvider().getCredentials();
        AmazonDynamoDB amazonDynamoDB = new AmazonDynamoDBClient(credentials);
        amazonDynamoDB.setRegion(Region.getRegion(Regions.CN_NORTH_1));

        System.out.println(amazonDynamoDBEndpoint);

        if (!StringUtils.isEmpty(amazonDynamoDBEndpoint)) {
            amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint);
        }
        return amazonDynamoDB;
    }

    @Override
    public void setEnvironment(Environment environment) {
        String env = environment.getProperty("ENV");
//        String env = "prod";
        if (env != null) {
            if (env.equals("test")) {
                amazonDynamoDBEndpoint = "http://dynamo.kehuilai.domain:8989";
                System.out.println(amazonDynamoDBEndpoint);
            } else if (env.equals("dev")) {
                amazonDynamoDBEndpoint = "http://localhost:8000";
                System.out.println(amazonDynamoDBEndpoint);
            }
        }
    }
}